package view 
{
	/**
	 * @author Alejandro
	 */
	
	import flash.display.Sprite;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.display.Loader;
	import flash.net.URLRequest;
	import flash.events.MouseEvent;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	 
	public class Player extends Sprite {
		
			
		public var states:Array = new Array();
		private var imagesAmount:Number;
		private var loadedAmount:Number;
		private var stateDisplayed:uint;
		
		
		public function Player(){
			//precondicion: las imagenes no pueden exceder la cantidad 99 por juego de animacion.
			imagesAmount = 16;
			loadedAmount = 0;
			var pathAndPrefix:String = "media/der/der_";
			var extension:String = ".png";
			var slot:uint;
			var slotT:uint = 0;
			for (slot = 0; slot < imagesAmount; slot++ ) {
				var url:String = pathAndPrefix + complete((slot + 1), 2) + extension;
			    var loader:Loader = new Loader();
				var loadFunction:Function = function(e:Event):void {
					var slotT2:uint = slotT++;
					addImage(e.target.content, slotT2);
				}
			    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadFunction);
			    loader.load(new URLRequest(url));
			}			
			graphics.beginFill(0xFFFFFF);
			graphics.drawRect(0, 0, 51, 59);
			graphics.endFill();
		}
		
		private function addImage(image:DisplayObject, slot:uint):void {
			trace("se incerta una imagen en el slot " + slot);
			states[slot] = image;
			//image.visible = false;
			loadedAmount++;
			if (loadedAmount >= imagesAmount) {
				for each(var state:DisplayObject in states) {
					addChild(state);					
				}
				this.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
					for each(var state:DisplayObject in states) {
						state.visible = false;	
					}
					
					stateDisplayed = 1;
					states[0].visible = true;
					var miTimer:Timer = new Timer(300);
					miTimer.addEventListener(TimerEvent.TIMER, function(event:TimerEvent):void {
					//addEventListener(Event.ENTER_FRAME, function(event:Event):void {
						if (stateDisplayed >= imagesAmount) {
							states[imagesAmount - 1].visible = false;
							states[0].visible = true;
							stateDisplayed = 1
						}
						else{
							states[stateDisplayed - 1].visible = false;
							states[stateDisplayed].visible = true;
							stateDisplayed++;
						}
					})
					miTimer.start();
				});
			}
		}
		
		public function complete(num:int, size:int):String{
			var res:String = String(num);
			for (var i:int = res.length; i < size; i++) {
				res = "0" + res;
			}
			return res;
		}
		
		//this.addEventListener()
		
		
	}
}